package com.sinocare.project.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sinocare.project.common.entity.JWTResult;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtil {

    //定义token返回头部
    public static final String AUTH_HEADER_KEY = "Authorization";

    //token前缀
//    public static final String TOKEN_PREFIX = "Bearer ";

    //签名密钥
    public static final String KEY = "q3Dt6w9z$C&eF)J@NcQf^TjWnZr4u7x)$@m";

    //有效期默认为 2hour
//    public static final Long EXPIRATION_TIME = 1000L*60*60*2;
    /**
     * 生成token
     * @param map //传入payload
     * @return 返回token
     */
    public static String getToken(Map<String, Object> map){	//map中放用户信息

        JWTCreator.Builder builder = JWT.create();
//遍历
        map.forEach((k,v) -> {
            builder.withClaim(k, v.toString());
        });

//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.SECOND, 7);	//7秒钟有效期
//        builder.withExpiresAt(instance.getTime());

        return builder.sign(Algorithm.HMAC256(KEY));
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
    }

    /**
     * 获取token中的payload
     * @param token
     * @return
     */
    public static JWTResult getToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
        JWTResult result = new JWTResult();
        result.setUserId(verify.getClaim("userId").asString());
        result.setRoleName(verify.getClaim("roleName").asString());
        return result;
    }

    public static void main(String[] args) {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("userId","1");
//        map.put("userName","as");
//        map.put("roleName","admin");
//        String token = JwtTokenUtil.getToken(map);
//        System.out.println(token);
//        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlTmFtZSI6ImFkbWluIiwidXNlck5hbWUiOiJhcyIsInVzZXJJZCI6IjEifQ.c91ZU5LEcYvl7uBFq1BU5MNFvwbWYGge7G5B7iFFPHc";
//        DecodedJWT token1 = JwtTokenUtil.getToken(token);
//        System.out.println(token1.getClaim("userId").asString());
//        System.out.println(token1.getClaim("userName").asString());
//        System.out.println(token1.getClaim("roleName").asString());
    }
}